﻿/* Copyright 2007-2008 dnAnalytics Project.
 *
 * Contributors to this file:
 * Jurgen Van Gael
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 
 * * Redistributions of source code must retain the above copyright notice, this 
 *   list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright notice, 
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 * * Neither the name of the dnAnalytics Project nor the names of its contributors
 *   may be used to endorse or promote products derived from this software without
 *   specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using dnAnalytics.Math;
using dnAnalytics.Properties;

namespace dnAnalytics.Statistics.Distributions
{
    /// <summary>
    /// The Gamma distribution is a distribution over the positive real numbers. It is parameterized by a shape
    /// parameter a > 0 and an inverse scale parameter b > 0. The pdf is
    /// 
    ///     p(x) = \frac{b^a}{\Gamma(a)} x^{a-1} \exp{-bx}.
    /// 
    /// The following degenerate case is special: when the precision is known, the precision shape will encode
    /// the value of the precision while the precision inverse scale is positive infinity.
    /// </summary>
    /// <remarks>The distribution will use the <see cref="System.Random"/> by default. 
    /// Users can set the random number generator by using the <see cref="RandomNumberGenerator"/> property.
    /// 
    /// The statistics classes will check all the incoming parameters whether they are in the allowed
    /// range. This might involve heavy computation. Optionally, by setting Control.CheckDistributionParameters
    /// to false, all parameter checks can be turned off.</remarks>
    public class Gamma : IContinuousDistribution
    {
        // Gamma shape parameter.
        private readonly double mShape;

        // Gamma scale parameter.
        private readonly double mInvScale;

        /// <summary>
        /// Constructs a Gamma distribution.
        /// </summary>
        /// <param name="shape">The shape of the Gamma distribution.</param>
        /// <param name="invScale">The inverse scale of the Gamma distribution.</param>
        public Gamma(double shape, double invScale)
        {
            if (Control.CheckDistributionParameters)
            {
                CheckParameters(shape, invScale);
            }

            mShape = shape;
            mInvScale = invScale;
            RandomNumberGenerator = new System.Random();
        }

        /// <summary>
        /// The shape parameter.
        /// </summary>
        public double Shape
        {
            get { return mShape; }
        }

        /// <summary>
        /// The scale parameter.
        /// </summary>
        public double Scale
        {
            get { return 1.0 / mInvScale; }
        }

        /// <summary>
        /// The inverse scale parameter.
        /// </summary>
        public double InvScale
        {
            get { return mInvScale; }
        }

        /// <summary>
        /// A string representation of the distribution.
        /// </summary>
        public override string ToString()
        {
            return "Gamma(Shape = " + mShape + ", Inverse Scale = " + mInvScale + ")";
        }

        #region IDistribution Members

        /// <summary>
        /// The mean of the distribution.
        /// </summary>
        /// <value></value>
        public double Mean
        {
            get
            {
                if (Double.IsPositiveInfinity(mInvScale))
                {
                    return mShape;
                }
                else
                {
                    return mShape / mInvScale;
                }
            }
        }

        /// <summary>
        /// The standard deviation of the distribution.
        /// </summary>
        /// <value></value>
        public double StdDev
        {
            get
            {
                if (Double.IsPositiveInfinity(mInvScale))
                {
                    return 0.0;
                }
                else
                {
                    return System.Math.Sqrt(mShape/(mInvScale*mInvScale));
                }
            }
        }

        /// <summary>
        /// The variance of the distribution.
        /// </summary>
        /// <value></value>
        public double Variance
        {
            get
            {
                if (Double.IsPositiveInfinity(mInvScale))
                {
                    return 0.0;
                }
                else
                {
                    return mShape / (mInvScale * mInvScale);
                }
            }
        }

        /// <summary>
        /// The entropy of the distribution.
        /// </summary>
        /// <value></value>
        public double Entropy
        {
            get
            {
                if (Double.IsPositiveInfinity(mInvScale))
                {
                    return 0.0;
                }
                else
                {
                    return mShape - System.Math.Log(mInvScale) + SpecialFunctions.GammaLn(mShape) + (1.0 - mShape)*SpecialFunctions.DiGamma(mShape);
                }
            }
        }

        /// <summary>
        /// Gets or sets the random number generator.
        /// </summary>
        /// <value>The random number generator used to generate a random sample.</value>
        public System.Random RandomNumberGenerator { get; set; }

        #endregion

        #region IContinuousSamplingDistribution Members

        /// <summary>
        /// The mode of the distribution.
        /// </summary>
        /// <value></value>
        public double Mode
        {
            get
            {
                if (Double.IsPositiveInfinity(mInvScale))
                {
                    return mShape;
                }
                else
                {
                    return (mShape - 1.0)/mInvScale;
                }
            }
        }

        /// <summary>
        /// The median of the distribution.
        /// </summary>
        /// <value></value>
        public double Median
        {
            get { throw new NotImplementedException(); }
        }

        /// <summary>
        /// Evaluates the probability density function for the Gamma distribution.
        /// </summary>
        /// <param name="x">The location in the domain where we want to evaluate the probability density function.</param>
        /// <returns></returns>
        public double Density(double x)
        {
            if (Double.IsPositiveInfinity(mInvScale))
            {
                if (x == mShape)
                {
                    return Double.PositiveInfinity;
                }
                else
                {
                    return 0.0;
                }
            }
            else
            {
                return System.Math.Pow(mInvScale, mShape) * System.Math.Pow(x, mShape - 1.0) * System.Math.Exp(-mInvScale * x) / SpecialFunctions.Gamma(mShape);
            }            
        }

        /// <summary>
        /// Samples a Gamma distributed random variable.
        /// </summary>
        public double Sample()
        {
            return SampleGamma(RandomNumberGenerator, mShape, mInvScale);
        }

        /// <summary>
        /// Samples an array of Gamma distributed random variables.
        /// </summary>
        /// <param name="n">The number of variables needed.</param>
        public double[] Sample(int n)
        {
            return DoSample(RandomNumberGenerator, n, mShape, mInvScale);
        }

        #endregion

        /// <summary>
        /// Evaluates the cumulative distribution function for the Gamma distribution.
        /// </summary>
        public double CumulativeDistribution(double x)
        {
            if (Double.IsPositiveInfinity(mInvScale))
            {
                if (x >= mShape)
                {
                    return 1.0;
                }
                else
                {
                    return 0.0;
                }
            }
            else
            {
                return SpecialFunctions.IncompleteGamma(mShape, x * mInvScale, true);
            }            
        }

        /// <summary>
        /// Evaluates the logarithm of the probability density function.
        /// </summary>
        public double DensityLn(double x)
        {
            if (Double.IsPositiveInfinity(mInvScale))
            {
                if (x == mShape)
                {
                    return Double.PositiveInfinity;
                }
                else
                {
                    return Double.NegativeInfinity;
                }
            }
            else
            {
                return mShape * System.Math.Log(mInvScale) + (mShape - 1.0) * System.Math.Log(x) - mInvScale * x - SpecialFunctions.GammaLn(mShape);
            }
        }

        /// <summary>
        /// Sampling implementation based on:
        /// "A Simple Method for Generating Gamma Variables" - Marsaglia &amp; Tsang
        /// ACM Transactions on Mathematical Software, Vol. 26, No. 3, September 2000, Pages 363–372.
        /// </summary>
        /// <param name="rnd">The random number generator to use.</param>
        /// <param name="shape">The shape of the Gamma distribution.</param>
        /// <param name="invScale">The inverse scale of the Gamma distribution.</param>
        /// <returns></returns>
        protected static double SampleGamma(System.Random rnd, double shape, double invScale)
        {
            if (Double.IsPositiveInfinity(invScale))
            {
                return shape;
            }
            else
            {
                double a = shape;
                double alphafix = 1.0;

                // Fix when alpha is less than one.
                if (shape < 1.0)
                {
                    a = shape + 1.0;
                    alphafix = System.Math.Pow(rnd.NextDouble(), 1.0 / shape);
                }

                double d = a - 1.0 / 3.0;
                double c = 1.0 / System.Math.Sqrt(9.0 * d);
                while (true)
                {
                    double x = Normal.Sample(rnd, 0.0, 1.0);
                    double v = 1.0 + c * x;
                    while (v <= 0.0)
                    {
                        x = Normal.Sample(rnd, 0.0, 1.0);
                        v = 1.0 + c * x;
                    }
                    v = v * v * v;
                    double u = rnd.NextDouble();
                    x = x * x;
                    if (u < 1.0 - 0.0331 * x * x)
                    {
                        return alphafix * d * v / invScale;
                    }
                    if (System.Math.Log(u) < 0.5 * x + d * (1.0 - v + System.Math.Log(v)))
                    {
                        return alphafix * d * v / invScale;
                    }
                }
            }
        }

        /// <summary>
        /// Samples a Gamma distributed random variable.
        /// </summary>
        /// <param name="rnd">The random number generator to use.</param>
        /// <param name="shape">The shape of the Gamma distribution.</param>
        /// <param name="invScale">The inverse scale of the Gamma distribution.</param>
        public static double Sample(System.Random rnd, double shape, double invScale)
        {
            if (Control.CheckDistributionParameters)
            {
                CheckParameters(shape, invScale);
            }

            return SampleGamma(rnd, shape, invScale);
        }

        /// <summary>
        /// Samples an array of Gamma distributed random variables.
        /// </summary>
        /// <param name="rnd">The random number generator to use.</param>
        /// <param name="n">The number of variables needed.</param>
        /// <param name="shape">The shape of the Gamma distribution.</param>
        /// <param name="invScale">The inverse scale of the Gamma distribution.</param>
        public static double[] Sample(System.Random rnd, int n, double shape, double invScale)
        {
            if (Control.CheckDistributionParameters)
            {
                CheckParameters(shape, invScale);
            }

            return DoSample(rnd, n, shape, invScale);
        }

        /// <summary>
        /// Check the parameters of the Gamma distribution.
        /// </summary>
        /// <param name="shape">The shape of the Gamma distribution.</param>
        /// <param name="invScale">The inverse scale of the Gamma distribution.</param>
        /// <exception cref="ArgumentOutOfRangeException">If any of the Gamma parameters are non-positive.</exception>
        private static void CheckParameters(double shape, double invScale)
        {
            if (shape <= 0.0)
            {
                throw new ArgumentOutOfRangeException("a", Resources.NotPositive);
            }
            if (invScale <= 0.0)
            {
                throw new ArgumentOutOfRangeException("b", Resources.NotPositive);
            }
        }


        /// <summary>
        /// Samples an array of Gamma distributed random variables.
        /// </summary>
        /// <param name="rnd">The random number generator to use.</param>
        /// <param name="n">The number of variables needed.</param>
        /// <param name="shape">The shape of the Gamma distribution.</param>
        /// <param name="invScale">The inverse scale of the Gamma distribution.</param>
        private static double[] DoSample(System.Random rnd, int n, double shape, double invScale)
        {
            double[] arr = new double[n];
            for (int i = 0; i < n; i++)
            {
                arr[i] = SampleGamma(rnd, shape, invScale);
            }
            return arr;
        }
    }
}